package cn.cloud.search.server.query_creater.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.util.Version;

import cn.cloud.search.bean.config.Config;
import cn.cloud.search.bean.config.DomainConfig;
import cn.cloud.search.bean.config.FieldConfig;
import cn.cloud.search.bean.query.QueryRequestInfo;
import cn.cloud.search.server.query_creater.IFieldQueryCreator;

public class FieldQueryCreator implements IFieldQueryCreator {

	private static final Logger log = Logger.getLogger(FieldQueryCreator.class);

	private Config config;
	
	private String allType;
	
	Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
    
	



	public Config getConfig() {
		return config;
	}



	public void setConfig(Config config) {
		this.config = config;
	}



	public String getAllType() {
		return allType;
	}



	public void setAllType(String allType) {
		this.allType = allType;
	}



	public Query creater(String query_words, String types) {
		log.info("query types is:"+types);
		BooleanQuery r_q = new BooleanQuery();
		List<Query> q_list = new ArrayList<Query>();
		String words = types;
		if(QueryRequestInfo.ALL_TYPE.equals(types.toUpperCase()))
			words = allType;
		String[] t_items = words.split("\\|");
		for(String t:t_items){
			DomainConfig dc = config.getDomainByKey(t);
			log.debug("DomainConfig is:"+t+"-"+dc);
			if(null!=dc){
				for(FieldConfig fc:dc.getField_config_list()){
					Query q = createFieldQueryByConfig(fc,query_words);
					if(null!=q)
						q_list.add(q);
				}
			}
		}
		for(Query q:q_list){
			r_q.add(q,Occur.SHOULD);
		}
		return r_q;
	}
	
	private Query createFieldQueryByConfig(FieldConfig fc,String qurey_words){
		
		Query q = null;
		log.debug("field query is:"+fc.getName());
		if(FieldConfig.IS_QUERY_FIELD==fc.getIsQueryField()){
			QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, fc.getName(), analyzer);
			try {
				q = parser.parse(qurey_words);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.info("create field query by:["+fc.getName()+","+qurey_words+"] is err:"+e,e);
			}
		}
		
		return q;
	}

}
